package com.sgr.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.sgr.dao.AcessoDao;
import com.sgr.model.Acesso;

public class AcessoDaoImpl implements AcessoDao{
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory){
		this.sessionFactory = sessionFactory;
	}
	
	public Session getCurrentSession(){
		return this.sessionFactory.getCurrentSession();
	}
	
	@Override
	@Transactional(readOnly = false)
	public void save(Acesso acesso) {
		getCurrentSession().save(acesso);
	}

	@Override
	@Transactional(readOnly = false)
	public void update(Acesso acesso) {
		getCurrentSession().update(acesso);
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(Acesso acesso) {
		getCurrentSession().delete(acesso);
	}

	@Override
	@Transactional(readOnly = true)
	public List findByUsername(String login) {
		Criteria query = getCurrentSession().createCriteria(getClass());
		Criterion condition = Restrictions.like("login_aces", login);
		query.add(condition);
		return query.list();
	}
	
	@Override
	@Transactional(readOnly = true)
	public Long count(){
		Long rows = (Long) getCurrentSession().createCriteria(Acesso.class).setProjection(Projections.rowCount()).uniqueResult();
		return rows;
	}

	@Override
	@Transactional(readOnly = true)
	public List findAll() {
		List acessos = getCurrentSession().createQuery("from Acesso").list();
		return acessos;
	}
	
	@Override
	@Transactional(readOnly = true)
	public Acesso findByPk(int id){
		Acesso acesso =  (Acesso) getCurrentSession().createCriteria(Acesso.class).add(Restrictions.eq("id", id)).uniqueResult();
		return acesso;
	}

}
